package wechat.start.wechatstart.util;

import com.thoughtworks.xstream.XStream;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import wechat.start.wechatstart.entity.*;
import wechat.start.wechatstart.enums.WeChatDevParams;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by WuJiXian on 2020/12/4 22:20
 */
@Slf4j
public class WechatUtil {

    private static AccessToken at;

    /**
     * 获取AccessToken
     */
    public static String getAccessToken() {
        if (at == null || at.isExpired()) {
            at = getToken();
        }
        return at.getAccessToken();
    }

    private static AccessToken getToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + WeChatDevParams.APP_ID.getValue() +"&secret=" + WeChatDevParams.APP_SECRET.getValue();
        String tokenStr = httpsRequest(url, "GET", null);
        try {
            JSONObject jsonObject = new JSONObject(tokenStr);
            String accessToken = jsonObject.getString("access_token");
            String expiresIn = jsonObject.getString("expires_in");
            at = new AccessToken(accessToken, expiresIn);
        } catch (JSONException e) {
            log.error("获取用户accessToken失败: " + e.getMessage());
            e.printStackTrace();
        }
        return at;

    }

    /**
     * 对消息的回复(响应)处理
     * @param requestMap
     * @return xml数据
     */
    public static String getResponse(Map<String, String> requestMap) {
        // 根据MsgType判断是什么类型的消息，然后再去构造响应的实体类
        String msgType = requestMap.get("MsgType");
        BaseMessage baseMessage = null;
        switch (msgType) {
            case "text" :// 文本
                baseMessage = dealTextMessage(requestMap);
                break;
            case "image" :// 图片
                break;
            case "voice" :// 语音
                break;
            case "video" :// 视频
                break;
            case "music" :
                break;
            case "news" :// 图文消息
                break;
            case "event" :// 事件推送
                baseMessage = dealEventMessage(requestMap);
                break;
        }
        // 这里只对文本消息进行了处理
        if (baseMessage != null) {
            return beanToXml(baseMessage);
        } else
            return null;

    }

    /**
     * 处理事件推送
     * @param requestMap
     * @return
     */
    private static BaseMessage dealEventMessage(Map<String, String> requestMap) {
        String eventType = requestMap.get("Event");
        BaseMessage baseMessage = null;
        String eventKey = requestMap.get("EventKey");
        switch (eventType) {
            case "CLICK" :
                baseMessage = new TextMessage(requestMap, "点击事件的eventKey：" + eventKey);
                break;
            case "VIEW" :
                baseMessage = new TextMessage(requestMap, "跳转的url为：：" + eventKey);
                break;
        }
        return baseMessage;
    }

    /**
     * 处理用户文本消息
     * @param requestMap
     * @return
     */
    private static BaseMessage dealTextMessage(Map<String, String> requestMap) {
        String content = requestMap.get("Content");
        if ("图文".equals(content)) {
            // 当用户发送“图文”时，回复用户一条图文消息
            List<Articles> articles = new ArrayList<>();
            Articles article = new Articles("祥仔的博客", "keep studying！", "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3482128345,2137456532&fm=26&gp=0.jpg", "https://blog.csdn.net/qq_30591155");
            articles.add(article);
            return new NewsMessage(requestMap, articles);
        } else {
            return new TextMessage(requestMap, "嗯，你说的对！");
        }
    }

    /**
     * bean对象转微信响应消息的XML形式
     * @param baseMessage
     * @return
     */
    private static String beanToXml(BaseMessage baseMessage) {
        String xml = null;
        if (baseMessage != null) {
            XStream xStream = new XStream();
            //　设置XStreamAlias注解要处理的类
            xStream.processAnnotations(baseMessage.getClass());
            xml = xStream.toXML(baseMessage);
        }
        return xml;
    }

    /**
     * 解析xml数据
     * @param in
     * @return
     * @throws DocumentException
     */
    public static Map<String, String> parseXml(InputStream in) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(in);
        Map<String, String> map = new HashMap<>();
        Element rootElement = document.getRootElement();
        List<Element> elements = rootElement.elements();
        for (Element e : elements) {
            map.put(e.getName(), e.getStringValue());
        }
        return map;
    }

    /**
     * 发起https请求并获取结果
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr 提交的数据
     * @return json字符串
     */
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes(StandardCharsets.UTF_8));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
        } catch (ConnectException ce) {
            log.error("Weixin server connection timed out.");
        } catch (Exception e) {
            log.error("https request error:{1}", e);
        }
        return buffer.toString();
    }

}
